package solution._0050._0056;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

/**
 * Created by chen_snow
 * Date: 2021/6/18 22:41
 * Description: 合并区间
 */
public class Solution {
    public int[][] merge(int[][] intervals) {

        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] != o2[0]) {
                    return o1[0] - o2[0];
                }
                return o1[1] - o2[1];
            }
        });

        ArrayList<int[]> data = new ArrayList<>();

        int left = intervals[0][0];
        int right = intervals[0][1];

        for (int i = 1; i < intervals.length; i++) {
            if (right < intervals[i][0]) {
                data.add(new int[]{left, right});
                left = intervals[i][0];
                right = intervals[i][1];
                continue;
            }

            right = Math.max(right, intervals[i][1]);
        }
        data.add(new int[]{left, right});

//        for (int i = 0; i < intervals.length; i++) {
//            int left = intervals[i][0];
//            int right = intervals[i][1];
//
//            if (i == 0 || data.get(data.size() - 1)[1] < left) {
//                data.add(new int[]{left, right});
//            } else {
//                data.get(data.size() - 1)[1] = Math.max(data.get(data.size() - 1)[1], right);
//            }
//
//        }
        return data.toArray(new int[data.size()][]);
    }
}
